package com.education.ai.service.impl;

import com.education.ai.entity.Admin;
import com.education.ai.dao.AdminDao;
import com.education.ai.service.AdminService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 管理员服务实现类
 */
@Service
public class AdminServiceImpl implements AdminService {

    private static final Logger logger = LoggerFactory.getLogger(AdminServiceImpl.class);

    @Autowired
    private AdminDao adminDao;

    @Override
    @Transactional
    public Admin saveAdmin(Admin admin) {
        return adminDao.save(admin);
    }

    @Override
    @Transactional
    public Admin updateAdmin(Admin admin) {
        adminDao.update(admin);
        return admin;
    }

    @Override
    public Optional<Admin> findById(Long id) {
        return adminDao.findById(id);
    }

    @Override
    public Optional<Admin> findByAdminId(String adminId) {
        return adminDao.findByAdminId(adminId);
    }

    @Override
    public List<Admin> findAllAdmins() {
        return adminDao.findAll();
    }

    @Override
    @Transactional
    public void deleteAdmin(Long id) {
        adminDao.delete(id);
    }

    @Override
    public List<Admin> findByNameContaining(String namePart) {
        return adminDao.findByNameContaining(namePart);
    }

    @Override
    public Map<String, Object> login(String adminId, String password) {
        logger.info("管理员登录尝试: {}", adminId);
        Map<String, Object> result = new HashMap<>();
        
        Optional<Admin> optionalAdmin = adminDao.findByAdminId(adminId);
        if (!optionalAdmin.isPresent()) {
            logger.warn("登录失败: 管理员ID {} 不存在", adminId);
            result.put("success", false);
            result.put("message", "管理员不存在");
            return result;
        }
        
        Admin admin = optionalAdmin.get();
        
        // 密码验证 - 简单比较而不是密码编码器
        if (!password.equals(admin.getPassword())) {
            logger.warn("登录失败: 管理员 {} 密码错误", adminId);
            result.put("success", false);
            result.put("message", "密码错误");
            return result;
        }
        
        // 更新最后登录时间
        admin.setLastLoginTime(LocalDateTime.now());
        adminDao.update(admin);
        
        // 登录成功
        logger.info("管理员 {} 登录成功", adminId);
        result.put("success", true);
        result.put("admin", admin);
        
        return result;
    }
} 